package com.ympc.controller;

import com.ympc.pojo.Student;
import com.ympc.pojo.Teacher;
import com.ympc.pojo.Users;
import com.ympc.service.StudentService;
import com.ympc.service.TeacherService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 教师管理控制器
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {
    
    @Resource
    private TeacherService teacherService;
    
    @Resource
    private StudentService studentService;
    
    /**
     * 教师主页
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String teacherHome(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        // 确保session中有teacher对象
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        if (teacher == null) {
            teacher = teacherService.getTeacherByUserId(user.getId());
            if (teacher == null) {
                // 如果还没有教师信息，创建一个空的教师对象
                teacher = new Teacher();
                teacher.setUserId(user.getId());
            }
            session.setAttribute("teacher", teacher);
        }
        
        model.addAttribute("teacher", teacher);
        return "teacher";
    }
    
    /**
     * 获取教师个人信息
     */
    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    public String getProfile(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null) {
            // 如果还没有教师信息，创建一个空的教师对象
            teacher = new Teacher();
            teacher.setUserId(user.getId());
        }
        model.addAttribute("teacher", teacher);
        return "teacher/profile";
    }
    
    /**
     * 更新教师个人信息
     */
    @RequestMapping(value = "/updateProfile", method = RequestMethod.POST)
    public String updateProfile(Teacher teacher, HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        try {
            Teacher existingTeacher = teacherService.getTeacherByUserId(user.getId());
            if (existingTeacher == null) {
                // 如果不存在，创建新记录
                teacher.setUserId(user.getId());
                boolean success = teacherService.createTeacherInfo(teacher);
                if (!success) {
                    model.addAttribute("error", "保存失败，请重试");
                    teacher.setUserId(user.getId());
                    model.addAttribute("teacher", teacher);
                    return "teacher/profile";
                }
                // 重新查询获取id
                teacher = teacherService.getTeacherByUserId(user.getId());
                if (teacher == null || teacher.getId() == null) {
                    model.addAttribute("error", "保存成功但查询失败，请刷新页面");
                    teacher = new Teacher();
                    teacher.setUserId(user.getId());
                    model.addAttribute("teacher", teacher);
                    return "teacher/profile";
                }
            } else {
                // 如果存在，更新记录
                teacher.setId(existingTeacher.getId());
                teacher.setUserId(user.getId());
                boolean success = teacherService.updateTeacherInfo(teacher);
                if (!success) {
                    model.addAttribute("error", "更新失败，请重试");
                    model.addAttribute("teacher", teacher);
                    return "teacher/profile";
                }
            }
            
            // 重新查询获取最新信息（包括头像）
            teacher = teacherService.getTeacherByUserId(user.getId());
            // 更新session中的教师信息
            session.setAttribute("teacher", teacher);
            
            model.addAttribute("message", "个人信息更新成功");
            model.addAttribute("teacher", teacher);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "保存时出错：" + e.getMessage());
            teacher.setUserId(user.getId());
            model.addAttribute("teacher", teacher);
        }
        return "teacher/profile";
    }
    
    /**
     * 设置页面
     */
    @RequestMapping(value = "/settings", method = RequestMethod.GET)
    public String settingsPage(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null) {
            // 如果还没有教师信息，创建一个空的教师对象
            teacher = new Teacher();
            teacher.setUserId(user.getId());
        }
        model.addAttribute("teacher", teacher);
        // 将教师信息添加到session，以便在所有页面使用
        session.setAttribute("teacher", teacher);
        return "teacher/settings";
    }
    
    /**
     * 上传头像
     */
    @RequestMapping(value = "/avatar/upload", method = RequestMethod.POST)
    public String uploadAvatar(@RequestParam("avatar") MultipartFile file,
                              HttpSession session,
                              Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            // 如果教师信息不存在或没有ID，先创建一个基本的教师记录
            teacher = new Teacher();
            teacher.setUserId(user.getId());
            boolean created = teacherService.createTeacherInfo(teacher);
            if (!created) {
                model.addAttribute("error", "教师信息不存在，且无法创建");
                teacher = new Teacher();
                teacher.setUserId(user.getId());
                model.addAttribute("teacher", teacher);
                return "teacher/settings";
            }
            // 重新查询获取ID
            teacher = teacherService.getTeacherByUserId(user.getId());
            if (teacher == null || teacher.getId() == null) {
                model.addAttribute("error", "教师信息创建失败");
                teacher = new Teacher();
                teacher.setUserId(user.getId());
                model.addAttribute("teacher", teacher);
                return "teacher/settings";
            }
        }
        
        if (file == null || file.isEmpty()) {
            model.addAttribute("error", "请选择要上传的头像文件");
            model.addAttribute("teacher", teacher);
            return "teacher/settings";
        }
        
        try {
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                model.addAttribute("error", "只能上传图片文件");
                model.addAttribute("teacher", teacher);
                return "teacher/settings";
            }
            
            // 创建上传目录
            String uploadDir = "uploads/avatars/";
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 生成文件名：教师ID_时间戳.扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = "teacher_" + teacher.getId() + "_" + System.currentTimeMillis() + extension;
            String filePath = uploadDir + fileName;
            Path destPath = uploadPath.resolve(fileName);
            
            // 保存文件
            Files.copy(file.getInputStream(), destPath);
            
            // 删除旧头像（如果存在）
            if (teacher.getAvatar() != null && !teacher.getAvatar().isEmpty()) {
                try {
                    Path oldAvatarPath = Paths.get(teacher.getAvatar());
                    if (Files.exists(oldAvatarPath)) {
                        Files.delete(oldAvatarPath);
                    }
                } catch (Exception e) {
                    // 忽略删除旧文件时的错误
                    e.printStackTrace();
                }
            }
            
            // 更新教师头像路径
            teacher.setAvatar(filePath);
            boolean success = teacherService.updateTeacherInfo(teacher);
            
            if (success) {
                model.addAttribute("message", "头像上传成功");
                // 重新查询教师信息
                teacher = teacherService.getTeacherByUserId(user.getId());
                // 更新session中的教师信息
                session.setAttribute("teacher", teacher);
            } else {
                model.addAttribute("error", "头像上传失败");
            }
            
            model.addAttribute("teacher", teacher);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "上传头像时出错：" + e.getMessage());
            model.addAttribute("teacher", teacher);
        }
        
        return "teacher/settings";
    }
    
    /**
     * 修改密码页面
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.GET)
    public String changePasswordPage() {
        return "teacher/changePassword";
    }
    
    /**
     * 修改密码
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    public String changePassword(@RequestParam String oldPassword, 
                                 @RequestParam String newPassword,
                                 HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        boolean success = teacherService.changePassword(user.getId(), oldPassword, newPassword);
        if (success) {
            model.addAttribute("message", "密码修改成功");
        } else {
            model.addAttribute("error", "旧密码错误或修改失败");
        }
        return "teacher/changePassword";
    }
    
    /**
     * 学生列表页面
     */
    @RequestMapping(value = "/student/list", method = RequestMethod.GET)
    public String studentList(Model model, 
                              @RequestParam(required = false) String className,
                              @RequestParam(required = false) String studentNumber) {
        List<Student> students;
        
        // 判断是否有筛选条件
        boolean hasClassName = className != null && !className.trim().isEmpty();
        boolean hasStudentNumber = studentNumber != null && !studentNumber.trim().isEmpty();
        
        if (hasClassName && hasStudentNumber) {
            // 同时按班级和学号筛选
            students = studentService.getStudentsByClassAndStudentNumber(className, studentNumber);
        } else if (hasClassName) {
            // 只按班级筛选
            students = studentService.getStudentsByClass(className);
        } else if (hasStudentNumber) {
            // 只按学号筛选
            students = studentService.getStudentsByStudentNumber(studentNumber);
        } else {
            // 没有筛选条件，显示所有学生
            students = studentService.getAllStudents();
        }
        
        model.addAttribute("students", students);
        model.addAttribute("className", className);
        model.addAttribute("studentNumber", studentNumber);
        return "teacher/studentList";
    }
    
    /**
     * 添加学生页面
     */
    @RequestMapping(value = "/student/add", method = RequestMethod.GET)
    public String addStudentPage() {
        return "teacher/addStudent";
    }
    
    /**
     * 添加学生
     */
    @RequestMapping(value = "/student/add", method = RequestMethod.POST)
    public String addStudent(Student student, Model model) {
        try {
            // 验证必填字段
            if (student.getStudentNumber() == null || student.getStudentNumber().trim().isEmpty()) {
                model.addAttribute("error", "学号不能为空");
                return "teacher/addStudent";
            }
            if (student.getName() == null || student.getName().trim().isEmpty()) {
                model.addAttribute("error", "姓名不能为空");
                return "teacher/addStudent";
            }
            
            boolean success = studentService.addStudent(student);
            if (success) {
                model.addAttribute("message", "学生添加成功！登录账号已自动创建：用户名=" + student.getStudentNumber() + "，密码=123456");
                return "redirect:/teacher/student/list";
            } else {
                model.addAttribute("error", "学生添加失败，可能是学号已存在或用户名已存在");
                return "teacher/addStudent";
            }
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "添加学生时出错：" + e.getMessage());
            return "teacher/addStudent";
        }
    }
    
    /**
     * 编辑学生页面
     */
    @RequestMapping(value = "/student/edit", method = RequestMethod.GET)
    public String editStudentPage(@RequestParam Integer id, Model model) {
        Student student = studentService.getStudentById(id);
        if (student == null) {
            model.addAttribute("error", "学生不存在");
            return "redirect:/teacher/student/list";
        }
        model.addAttribute("student", student);
        return "teacher/editStudent";
    }
    
    /**
     * 更新学生信息
     */
    @RequestMapping(value = "/student/update", method = RequestMethod.POST)
    public String updateStudent(Student student, Model model) {
        boolean success = studentService.updateStudent(student);
        if (success) {
            model.addAttribute("message", "学生信息更新成功");
            return "redirect:/teacher/student/list";
        } else {
            model.addAttribute("error", "学生信息更新失败");
            model.addAttribute("student", student);
            return "teacher/editStudent";
        }
    }
    
    /**
     * 删除学生
     */
    @RequestMapping(value = "/student/delete", method = RequestMethod.GET)
    public String deleteStudent(@RequestParam Integer id, Model model) {
        boolean success = studentService.deleteStudent(id);
        if (success) {
            model.addAttribute("message", "学生删除成功");
        } else {
            model.addAttribute("error", "学生删除失败");
        }
        return "redirect:/teacher/student/list";
    }
}

